import requests
from bs4 import BeautifulSoup
import re
import time
from datetime import datetime
from notify import send  # 导入青龙通知模块
##cron: 7 7 7 7 7
##new Env("漫漫看影视")

def get_month_range():
    """获取当前月份前后各两个月的YYYYMM格式列表（共5个月）"""
    current = datetime.now()
    months = []
    
    # 从当前月份前2个月到后2个月，共5个月
    for i in range(-2, 3):
        year = current.year
        month = current.month + i
        
        # 处理年份和月份的进位
        if month < 1:
            year -= 1
            month += 12
        elif month > 12:
            year += 1
            month -= 12
            
        months.append((year, month, f"{year}{month:02d}"))  # 返回(year, month, YYYYMM)
    
    return months

def extract_info_from_status(status):
    """从状态文本中提取集数和上映时间"""
    episode_info = "未知"
    release_date = "未知"
    
    if not status:
        return episode_info, release_date
    
    # 处理集数信息
    episode_match = re.search(r'(更新至第(\d+)集|第(\d+)集)', status)
    if episode_match:
        if episode_match.group(2):  # 匹配"更新至第X集"
            episode_info = f"更新至{episode_match.group(2)}集"
        else:  # 匹配"第X集"
            episode_info = f"第{episode_match.group(3)}集"
    
    # 处理上映时间信息
    date_match = re.search(r'(\d{4}年\d{1,2}月\d{0,2}日?|\d{4}/\d{1,2}/\d{1,2})', status)
    if date_match:
        release_date = date_match.group(1)
    elif "上映" in status:
        release_date = status.replace("上映：", "").strip()
    
    return episode_info, release_date

def scrape_tv_show_info(url):
    """爬取指定月份的电视剧信息"""
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer": "https://g.manmankan.com/",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.9"
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, 'html.parser')
        tv_shows = []
        
        for item in soup.select('div.jzfl li'):
            try:
                # 提取剧名
                title_link = item.select_one('p.jzfl-p2 a')
                title = title_link.text.strip() if title_link else "未知剧名"
                
                # 提取状态信息
                status_span = item.select_one('span.jzfl-p1-as2')
                status = status_span.text.strip() if status_span else ""
                
                # 分析状态信息
                episode_info, release_date = extract_info_from_status(status)
                
                tv_shows.append({
                    '剧名': title,
                    '集数': episode_info,
                    '上映时间': release_date
                })
                
            except Exception as e:
                print(f"解析单个电视剧时出错: {e}")
                continue
        
        # 获取月份标题
        month_title = "未知月份"
        title_tag = soup.select_one('div.rmzy h1')
        if title_tag:
            month_title = ' '.join(title_tag.text.strip().split())
        
        return {
            '月份标题': month_title,
            '电视剧列表': tv_shows
        }
        
    except requests.exceptions.RequestException as e:
        print(f"请求 {url} 出错: {e}")
        return None
    except Exception as e:
        print(f"解析 {url} 出错: {e}")
        return None

def format_console_output(tv_info, month_name):
    """格式化控制台输出"""
    if not tv_info or not tv_info['电视剧列表']:
        return f"{month_name}: 未获取到电视剧信息\n"
    
    output = f"\n{'-'*60}\n"
    output += f"月份: {tv_info['月份标题']}\n"
    output += f"{'序号':<5}{'剧名':<20}{'集数':<15}{'上映时间':<15}\n"
    output += "-"*60 + "\n"
    
    for idx, show in enumerate(tv_info['电视剧列表'], 1):
        output += f"{idx:<5}{show['剧名']:<20}{show['集数']:<15}{show['上映时间']:<15}\n"
    
    return output

def format_notification_content(all_results):
    """格式化综合通知内容"""
    if not all_results:
        return "未获取到任何电视剧信息"
    
    content = "📺 漫漫看电视剧综合信息\n\n"
    
    for month_name, tv_info in all_results:
        if not tv_info or not tv_info['电视剧列表']:
            content += f"📅 {month_name}: 无数据\n\n"
            continue
        
        content += f"📅 {tv_info['月份标题']}\n"
        
        for show in tv_info['电视剧列表']:
            content += f"🎬 {show['剧名']}\n"
            content += f"  集数: {show['集数']}\n"
            content += f"  上映: {show['上映时间']}\n"
        
        content += "\n"
    
    return content.strip()

def main():
    base_url = "https://g.manmankan.com/dy2013/dianshiju/"
    month_data = get_month_range()
    notification_title = "漫漫看电视剧综合信息"
    
    all_results = []
    all_console_output = []
    
    for year, month, month_ym in month_data:
        month_name = f"{year}年{month}月"
        url = f"{base_url}{month_ym}/"
        print(f"\n正在爬取 {month_name} 的电视剧信息...")
        
        tv_info = scrape_tv_show_info(url)
        time.sleep(5)  # 延时5秒
        
        if tv_info:
            # 控制台输出
            console_output = format_console_output(tv_info, month_name)
            print(console_output)
            all_console_output.append(console_output)
            
            # 保存结果用于综合通知
            all_results.append((month_name, tv_info))
        else:
            msg = f"{month_name}: 未能获取电视剧信息"
            print(msg)
            all_results.append((month_name, None))
    
    # 汇总所有控制台输出
    print("\n" + "="*60)
    print("所有月份电视剧信息汇总:")
    print("="*60)
    for output in all_console_output:
        print(output)
    
    # 发送统一综合通知
    notification_content = format_notification_content(all_results)
    send(notification_title, notification_content)

if __name__ == "__main__":
    main()